package cn.tedu.charging.order.consumer;

import cn.tedu.charging.common.pojo.message.DelayCheckMessage;
import cn.tedu.charging.common.pojo.po.ChargingBillFailPO;
import cn.tedu.charging.common.protocol.WebSocketMessage;
import cn.tedu.charging.order.dao.mapper.ChargingBillFailMapper;
import cn.tedu.charging.order.dao.mapper.ChargingBillSuccessMapper;
import cn.tedu.charging.order.webSocket.WebSocketServer;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DelayCheckConsumer {
    @Autowired
    private ChargingBillFailMapper chargingBillFailMapper;
    @Autowired
    private ChargingBillSuccessMapper chargingBillSuccessMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WebSocketServer webSocketServer;

    @RabbitListener(queues = "DELAY_BILL_DL_QUEUE")
    public void handleGunCheck(DelayCheckMessage message) {
        log.debug("延迟消息检查:{}", message);
        log.debug("添加抢锁流程");
        String lockKey = "charging:order:" + message.getOrderNo();
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, "", 5, TimeUnit.SECONDS);
        if (Boolean.FALSE.equals(result)) {
            log.debug("抢锁失败");
            return;
        }
        Boolean exist = checkSuccessOrFail(message.getOrderNo());
        if (!exist) {
            createFailBill(message);
            //远程调用生成优惠券
            //createUserCoupon(message.getUserId());
            //通知手机客户端，送你一张优惠券
            WebSocketMessage<String> webSocketMessage = new WebSocketMessage<>();
            webSocketMessage.setState(1);
            webSocketMessage.setMessage("fail");
            webSocketMessage.setData("B 您的订单创建失败，设备有故障，对不起，送您一张优惠券");
            webSocketServer.pushMessage(message.getUserId(), JSON.toJSONString(webSocketMessage));
        }
    }

    private void createFailBill(DelayCheckMessage message) {
        ChargingBillFailPO po = new ChargingBillFailPO();
        po.setBillId(message.getOrderNo());
        po.setUserId(message.getUserId());
        po.setGunId(message.getGunId());
        po.setVehicleId(message.getVehicleId());
        po.setDeleted(0);
        po.setCreateTime(new Date());
        po.setUpdateTime(new Date());
        po.setFailDesc("设备自检充电失败");
        chargingBillFailMapper.insert(po);
    }

    private Boolean checkSuccessOrFail(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bill_id", orderNo);
        Long successCount = chargingBillSuccessMapper.selectCount(queryWrapper);
        Long failCount = chargingBillFailMapper.selectCount(queryWrapper);
        if (successCount != null && failCount != null) {
            return successCount > 0 || failCount > 0;
        } else {
            return false;
        }
    }

}
